package com.sk.weichat.ui.me;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.bean.AddAttentionResult;
import com.sk.weichat.bean.Area;
import com.sk.weichat.bean.EventChatRemoveBlack;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.FriendHelper;
import com.sk.weichat.mvp.contract.PersonalCenterContract;
import com.sk.weichat.mvp.presenter.PersonalCenterPresenter;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.BaseLoginActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.tool.SingleImagePreviewActivity;
import com.sk.weichat.util.DateUtils;
import com.sk.weichat.util.DisplayUtil;
import com.sk.weichat.util.SystemUtil;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.sk.weichat.xmpp.listener.NewFriendListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * 个人信息页
 * create by swy 2019-06-20
 */
public class PersonalCenterActivity extends BaseLoginActivity implements NewFriendListener, PersonalCenterContract.BaseView, View.OnClickListener {

    public static final String KEY_FROM_ADD_TYPE = "KEY_FROM_ADD_TYPE";
    //1:二维码 2：名片 3：群组 4： 手机号搜索 5： 昵称搜索 6:其他方式添加
    public static final String FROM_ADD_TYPE_QRCODE = "1"; //二维码
    public static final String FROM_ADD_TYPE_CARD = "2"; //名片
    public static final String FROM_ADD_TYPE_GROUP = "3"; //群组
    public static final String FROM_ADD_TYPE_PHONE = "4"; //手机号搜索
    public static final String FROM_ADD_TYPE_NAME = "5"; //昵称搜索
    public static final String FROM_ADD_TYPE_OTHER = "6"; //其他方式添加

    private int mOffset = 0;
    private int mScrollY = 0;
    private String mUserId;
    private String mFromAddType;
    private String mLoginUserId;
    private PersonalCenterPresenter mPresenter;
    private boolean mIsMyInfo = true;//true 自己的个人信息，false他人的个人信息
    private TextView mTvName;
    private ImageView img_system_flag;
    private LinearLayout ll_signature, ll_basic_info;
    private TextView mTvSignature;
    private TextView mTvAnonymity;
    private CheckBox mCheckSex;
    private TextView mTvWarn;
    private TextView mTvAccount;
    private TextView mTvCreeteTime;
    private LinearLayout ll_center_city;
    private TextView mTvCity;
    private TextView mTvRelation;
    private RelativeLayout mLayoutSendMsg;
    private RelativeLayout mLayoutAttention;
    private ImageView mImgPhone;
    private LinearLayout ll_nickname;
    private TextView tv_nickname;
    private User mUser;
    private String mAddhaoyouid;
    private int mFriendState;

    public static final void start(Context context,String userid){
        Intent intent = new Intent(context, PersonalCenterActivity.class);
        intent.putExtra(AppConstant.EXTRA_USER_ID, userid);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_center);
        initActionBar();
        initView();
        ListenerManager.getInstance().addNewFriendListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mLoginUserId.equals(mUserId)) {//自己的个人信息
            mIsMyInfo = true;
            mPresenter.getUserInfo();
            ((ImageView) findViewById(R.id.iv_title_right)).setImageResource(R.mipmap.icon_person_edit);
            findViewById(R.id.layout_center_bottom).setVisibility(View.GONE);
        } else {//他人的个人信息
            mIsMyInfo = false;
            mPresenter.getOtherUserInfo(mUserId);
            /*屏蔽“悦聊团队”的个人信息编辑页面需要屏蔽 “...” 入口*/
            if (mUserId.equals(Friend.ID_SYSTEM_MESSAGE)) {
                findViewById(R.id.iv_title_right).setVisibility(View.GONE);
                img_system_flag.setVisibility(View.VISIBLE);
                ll_signature.setVisibility(View.GONE);
                ll_basic_info.setVisibility(View.GONE);
                mTvCity.setText("广西壮族自治区 南宁市");
            } else {
                img_system_flag.setVisibility(View.GONE);
                ll_signature.setVisibility(View.VISIBLE);
                ll_basic_info.setVisibility(View.VISIBLE);
                findViewById(R.id.iv_title_right).setVisibility(View.VISIBLE);
                ((ImageView) findViewById(R.id.iv_title_right)).setImageResource(R.drawable.icon_more_white);
            }
        }
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(Color.parseColor("#00000000"));

        findViewById(R.id.tv_title_center).setVisibility(View.GONE);
        ((ImageView) findViewById(R.id.iv_title_left)).setImageResource(R.mipmap.icon_back_white);
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        findViewById(R.id.iv_title_right).setOnClickListener(this);

    }

    private void initView() {
        mPresenter = new PersonalCenterPresenter(coreManager, this);
        if (getIntent() != null) {
            mUserId = getIntent().getStringExtra(AppConstant.EXTRA_USER_ID);
            mFromAddType = getIntent().getStringExtra(KEY_FROM_ADD_TYPE);
        }
        mLoginUserId = coreManager.getSelf().getUserId();

        mImgPhone = findViewById(R.id.img_center_photo);
        mTvName = findViewById(R.id.tv_center_name);
        ll_nickname = findViewById(R.id.ll_nickname);
        tv_nickname = findViewById(R.id.tv_nickname);
        img_system_flag = findViewById(R.id.img_system_flag);
        ll_signature = findViewById(R.id.ll_signature);
        ll_basic_info = findViewById(R.id.ll_basic_info);
        mTvSignature = findViewById(R.id.tv_center_signature);
        mTvAnonymity = findViewById(R.id.tv_center_anonymity);
        mTvWarn = findViewById(R.id.tv_center_warn);
        mTvAccount = findViewById(R.id.tv_center_account);
        mTvCreeteTime = findViewById(R.id.tv_center_create_time);
        ll_center_city = findViewById(R.id.ll_center_city);
        mTvCity = findViewById(R.id.tv_center_city);
        mTvRelation = findViewById(R.id.tv_center_relation);
        mCheckSex = findViewById(R.id.checkbox_center_sex);
        mLayoutSendMsg = findViewById(R.id.layout_center_msg_send);
        mLayoutAttention = findViewById(R.id.layout_center_attention);

//        mTvWarn.setOnClickListener(this);
        findViewById(R.id.img_center_copy).setOnClickListener(this);//复制
        findViewById(R.id.layout_center_msg_send).setOnClickListener(this);//发送消息
        mLayoutAttention.setOnClickListener(this);//关注
        findViewById(R.id.layout_center_photo_top).setOnClickListener(this);//点击头像

        //头部拉伸效果
        setHeaderMoving();
    }

    /**
     * 头部拉伸效果
     */
    private void setHeaderMoving() {
        final View parallax = findViewById(R.id.layout_center_photo);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        parallax.measure(w, h);
        float width = parallax.getMeasuredWidth();
        final RefreshLayout refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            }

            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
                mOffset = offset * 2;
                parallax.setTranslationY(offset / 2.0f - mScrollY);
                parallax.setScaleX((mOffset + width) / width);
                parallax.setScaleY((mOffset + width) / width);
            }
        });
    }

    @Override
    public void onNewFriendSendStateChange(String toUserId, NewFriendMessage message, int messageState) {
        if (messageState == ChatMessageListener.MESSAGE_SEND_SUCCESS) {
            msgSendSuccess(message, message.getPacketId());
        } else if (messageState == ChatMessageListener.MESSAGE_SEND_FAILED) {
            msgSendFailed(message.getPacketId());
        }
    }

    @Override
    public boolean onNewFriend(NewFriendMessage message) {
        return false;
    }

    @Override
    public void onClick(View v) {

        Intent intent;
        switch (v.getId()) {
            case R.id.iv_title_left://返回
                finish();
                break;

            case R.id.layout_center_photo_top://点击头像
                intent = new Intent(this, SingleImagePreviewActivity.class);
                intent.putExtra(AppConstant.EXTRA_IMAGE_URI, mUserId);
                startActivity(intent);
                break;

            case R.id.tv_center_warn:
            case R.id.iv_title_right://更多（他人）或编辑（自己）
                if (mIsMyInfo) {//编辑
                    intent = new Intent(this, PersonalCenterEditActivity.class);
                    startActivity(intent);
                } else {//更多
                    intent = new Intent(this, PersonalCenterMoreActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, mUserId);
                    startActivity(intent);
                }
                break;

            case R.id.layout_center_msg_send://发送消息
                Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, mUserId);
                MsgBroadcast.broadcastMsgUiUpdate(this);//刷新消息界面
                MsgBroadcast.broadcastMsgNumReset(this);
                intent = new Intent(mContext, ChatActivity.class);
                intent.putExtra(ChatActivity.FRIEND, friend);
                startActivity(intent);
                break;

            case R.id.layout_center_attention://关注
                doAddAttention();
                break;

            case R.id.img_center_copy:// 复制文字
                SystemUtil.copyText(getApplicationContext(), mTvAccount.getText().toString());
                ToastUtil.showToast(this, "复制成功");
                break;

        }
    }

    @Override
    public void onUpdateUI(User user) {
        mUser = user;
        if (mUserId.equals(Friend.ID_SYSTEM_MESSAGE)) {
            //加载本地图片
            Glide.with(mContext).load(R.mipmap.icon_mine_bg).placeholder(R.drawable.avatar_normal).into(mImgPhone);
        } else {
            AvatarHelper.getInstance().displayAvatar("", mUserId, mImgPhone, false);
        }

        if (user.getFriends() != null && !TextUtils.isEmpty(user.getFriends().getRemarkName())) {
            mTvName.setText(user.getFriends().getRemarkName());
            ll_nickname.setVisibility(View.VISIBLE);
            tv_nickname.setText(user.getNickName());
        } else {
            mTvName.setText(user.getNickName());
            ll_nickname.setVisibility(View.GONE);
//            tv_nickname.setText(user.getNickName());
        }

        if (!TextUtils.isEmpty(user.getDescription())) {
            mTvSignature.setText(user.getDescription());
        } else {
            mTvSignature.setText(getString(R.string.signature_describe_empty));
        }

        double latitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
        double longitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
        String distance = DisplayUtil.getDistanceInfo(latitude, longitude, mUser.getLoc());
        if (mUser.getSettings() == null) {
            mTvAnonymity.setVisibility(View.INVISIBLE);
        } else {
            if (mUser.getSettings().getShowLastLoginTime() == 1 && mUser.getSettings().getAllowQueryLoc() == 1) {//显示登录时间，距离
                if (TextUtils.isEmpty(distance)) {
                    mTvAnonymity.setText(TimeUtils.getFriendlyTimeDesc(this, user.getShowLastLoginTime()));
                } else {
                    mTvAnonymity.setText(distance + " · " + TimeUtils.getFriendlyTimeDesc(this, user.getShowLastLoginTime()));
                }

            } else if (mUser.getSettings().getShowLastLoginTime() == 1) {
                mTvAnonymity.setText(TimeUtils.getFriendlyTimeDesc(this, user.getShowLastLoginTime()));//只显示登录时间
            } else if (mUser.getSettings().getAllowQueryLoc() == 1) {//只显示距离
                if (TextUtils.isEmpty(distance)) {
                    mTvAnonymity.setVisibility(View.INVISIBLE);
                } else {
                    mTvAnonymity.setText(distance);
                }

            } else {
                mTvAnonymity.setText("隐身");
            }
        }

        if (user.getSex() == 0) {//女
            mCheckSex.setChecked(false);
        } else {
            mCheckSex.setChecked(true);
        }
        mCheckSex.setText(DateUtils.getAge(new Date(user.getBirthday() * 1000)) + "");

        mTvAccount.setText(user.getAccount());
        mTvCreeteTime.setText(TimeUtils.sk_time_s_long_2_str(user.getCreateTime()));

        if (mUserId.equals(Friend.ID_SYSTEM_MESSAGE)) {
            mTvCity.setText("广西壮族自治区 南宁市");
        } else {
            if (TextUtils.isEmpty(Area.getProvinceCityString(user.getProvinceId(), user.getAreaId()))) {
                ll_center_city.setVisibility(View.GONE);
            } else {
                ll_center_city.setVisibility(View.VISIBLE);
                mTvCity.setText(Area.getProvinceCityString(user.getProvinceId(), user.getAreaId()) + " " + Area.getCityAreaString(user.getCityId(), user.getAreaId()));
            }
        }


        mTvWarn.setClickable(false);
        if (mIsMyInfo) {
            mTvRelation.setText("自己");
        } else {

            if (user.getFriends() == null) {//没有聊过天的陌生人
                mTvRelation.setText("陌生人");
                mTvWarn.setVisibility(View.GONE);
                mLayoutAttention.setVisibility(View.VISIBLE);
                mLayoutSendMsg.setBackgroundResource(R.drawable.bg_btn_msg_send);
                mLayoutSendMsg.setClickable(true);
            } else if (user.getFriends().getBlacklist() == 1) { //拉黑
                mTvRelation.setText("拉黑");
                mTvWarn.setVisibility(View.VISIBLE);
                mTvWarn.setClickable(true);

                SpannableStringBuilder style = new SpannableStringBuilder();

                //设置文字
                style.append("你已把对方加入黑名单，移出黑名单或关注可正常聊天");

                //设置 "移出黑名单"点击事件
                ClickableSpan clickableSpan = new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        Intent intent = new Intent(PersonalCenterActivity.this, PersonalCenterMoreActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, mUserId);
                        startActivity(intent);
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(getResources().getColor(R.color.color_FCC23C));
                        ds.setUnderlineText(false);
                    }
                };
                //设置 "关注"点击事件
                ClickableSpan clickableSpan1 = new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        doAddAttention();
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(getResources().getColor(R.color.color_FCC23C));
                        ds.setUnderlineText(false);
                    }
                };
                //必须设置这句 才可点击超链接
                mTvWarn.setMovementMethod(LinkMovementMethod.getInstance());
                style.setSpan(clickableSpan, 11, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                style.setSpan(clickableSpan1, 17, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                mTvWarn.setText(style);
                mLayoutAttention.setVisibility(View.VISIBLE);
                mLayoutSendMsg.setBackgroundResource(R.drawable.bg_btn_msg_send_unable);
                mLayoutSendMsg.setClickable(false);
            } else if (user.getFriends().getIsBeenBlack() == 1) {//被拉黑
                mTvRelation.setText("被拉黑");
                if (user.getFriends().getStatus() == Friend.STATUS_ATTENTION) {//被拉黑且关注的状态要隐藏关注按钮
                    mLayoutAttention.setVisibility(View.GONE);
                } else {
                    mLayoutAttention.setVisibility(View.VISIBLE);
                }
                mTvWarn.setVisibility(View.VISIBLE);
                mTvWarn.setText(R.string.beblack_warn);
                mLayoutSendMsg.setBackgroundResource(R.drawable.bg_btn_msg_send_unable);
                mLayoutSendMsg.setClickable(false);
            } else if (user.getFriends().getStatus() == 0) {//聊过天的陌生人
                mTvRelation.setText("陌生人");
                mTvWarn.setVisibility(View.GONE);
                mLayoutAttention.setVisibility(View.VISIBLE);
                mLayoutSendMsg.setBackgroundResource(R.drawable.bg_btn_msg_send);
                mLayoutSendMsg.setClickable(true);
            } else if (user.getFriends().getStatus() == 2 || user.getFriends().getStatus() == 4) {// 好友
                mTvRelation.setText("好友");
                mTvWarn.setVisibility(View.GONE);
                mLayoutAttention.setVisibility(View.GONE);
                mLayoutSendMsg.setBackgroundResource(R.drawable.bg_btn_msg_send);
                mLayoutSendMsg.setClickable(true);

            } else if (user.getFriends().getStatus() == Friend.STATUS_ATTENTION) {//关注
                mTvRelation.setText("关注");
                mTvWarn.setVisibility(View.GONE);
                mLayoutAttention.setVisibility(View.GONE);
                mLayoutSendMsg.setBackgroundResource(R.drawable.bg_btn_msg_send);
                mLayoutSendMsg.setClickable(true);

            } else if (user.getFriends().getStatus() == Friend.STATUS_BE_ATTENTION) {//被关注
                mTvRelation.setText("粉丝");
                mTvWarn.setVisibility(View.GONE);
                mLayoutAttention.setVisibility(View.VISIBLE);
                mLayoutSendMsg.setBackgroundResource(R.drawable.bg_btn_msg_send);
                mLayoutSendMsg.setClickable(true);
            }

            //异常账号
            if (user.getStatus() != 1) {
                mTvWarn.setVisibility(View.VISIBLE);
                mTvWarn.setText(R.string.account_error);
                Glide.with(this).load(R.drawable.img_warmphone).into(mImgPhone);
                //mImgPhone.setImageResource(R.drawable.img_warmphone);
            }
        }
    }

    public void msgSendSuccess(NewFriendMessage message, String packet) {
        if (mAddhaoyouid != null && mAddhaoyouid.equals(packet)) {
            if (mFriendState == 1) {// 关系为关注
                Toast.makeText(getApplicationContext(), InternationalizationHelper.getString("JXAlert_SayHiOK"), Toast.LENGTH_SHORT).show();

                ChatMessage sayChatMessage = new ChatMessage();
                sayChatMessage.setContent(InternationalizationHelper.getString("JXFriendObject_WaitPass"));
                sayChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                // 各种Dao都是本地数据库的操作，
                // 这个是好友表里更新最后一条消息，
                FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, sayChatMessage);

                // 这个是新的好友界面用的，等验证什么的都在新的好友页面，
                NewFriendDao.getInstance().changeNewFriendState(mUser.getUserId(), Friend.STATUS_10);// 好友状态
                ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);

            } else if (mFriendState == 2) {//关系为好友
                Toast.makeText(getApplicationContext(), InternationalizationHelper.getString("JX_AddSuccess"), Toast.LENGTH_SHORT).show();

                NewFriendDao.getInstance().ascensionNewFriend(message, Friend.STATUS_FRIEND);
                FriendHelper.addFriendExtraOperation(mLoginUserId, mUser.getUserId());// 加好友

                ChatMessage addChatMessage = new ChatMessage();
                addChatMessage.setContent(InternationalizationHelper.getString("JXNearVC_AddFriends") + ":" + mUser.getNickName());
                addChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, addChatMessage);

                NewFriendDao.getInstance().changeNewFriendState(mUser.getUserId(), Friend.STATUS_22);//添加了xxx
                FriendDao.getInstance().updateFriendContent(mLoginUserId, mUser.getUserId(), InternationalizationHelper.getString("JXMessageObject_BeFriendAndChat"), XmppMessage.TYPE_TEXT, TimeUtils.sk_time_current_time());
                ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);

                CardcastUiUpdateUtil.broadcastUpdateUi(mContext);
            }

        }
    }

    public void msgSendFailed(String packet) {
        DialogHelper.dismissProgressDialog();
        if (packet.equals(mAddhaoyouid)) {
            Toast.makeText(this, R.string.tip_hello_failed, Toast.LENGTH_SHORT).show();
        }
    }


    // 点击加好友就调用这个方法，
    private void doAddAttention() {

        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", mUserId);
        if (TextUtils.isEmpty(mFromAddType)) {
            // 默认就是其他方式，
            mFromAddType = String.valueOf(FROM_ADD_TYPE_OTHER);
        }
        params.put("fromAddType", mFromAddType);
        DialogHelper.showDefaulteMessageProgressDialog(this);

        // 首先是调接口，
        HttpUtils.get().url(coreManager.getConfig().FRIENDS_ATTENTION_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<AddAttentionResult>(AddAttentionResult.class) {

                    @Override
                    public void onResponse(ObjectResult<AddAttentionResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1 && result.getData() != null) {

                            Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, mUserId);

                            if (result.getData().getType() == 1 || result.getData().getType() == 3) {//关注
                                mFriendState = 1;

                                if (friend != null
                                        && friend.getReplyStatus() != Friend.STATUS_REPLAY_BOTH//未回复
                                        && (mUser.getFriends() == null || mUser.getFriends().getIsBeenBlack() != 1)//未被拉黑
                                        && result.getData().getIsFollowed() == 0) {//未关注过的发送打招呼消息

                                    doSayHello(friend, coreManager.getSelf().getNickName() + "关注了你");
                                }
                                mPresenter.getOtherUserInfo(mUserId);

                                if (mUser.getFriends() != null && mUser.getFriends().getIsBeenBlack() == 1) {//被拉黑的关注时状态还是被拉黑
                                    FriendDao.getInstance().updateBeBlack(mLoginUserId, mUserId, 1);
                                    FriendDao.getInstance().updateFriendStatus(mLoginUserId, mUserId, Friend.STATUS_ATTENTION);
                                } else {
                                    FriendDao.getInstance().updateBeBlack(mLoginUserId, mUserId, 0);
                                    FriendDao.getInstance().updateFriendStatus(mLoginUserId, mUserId, Friend.STATUS_ATTENTION);
                                }

                            } else if (result.getData().getType() == 2 || result.getData().getType() == 4) {// 已经是好友了
                                mFriendState = 2;
                                if (friend != null
                                        && friend.getReplyStatus() != Friend.STATUS_REPLAY_BOTH//未回复
                                        && (mUser.getFriends() == null || mUser.getFriends().getIsBeenBlack() != 1)//未被拉黑
                                        && result.getData().getIsFollowed() == 0) {// 未回复并且未关注过的发送打招呼消息

                                    doSayHello(friend, coreManager.getSelf().getNickName() + "关注了你，你们已经是好友，可以互发语音");
                                }
                                mPresenter.getOtherUserInfo(mUserId);
                                FriendDao.getInstance().updateFriendStatus(mLoginUserId, mUserId, Friend.STATUS_FRIEND);
                            }
                            ToastUtil.showToast(mContext, "关注对方成功");

                        } else {
                            Toast.makeText(PersonalCenterActivity.this, result.getResultMsg() + "", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        Toast.makeText(mContext, R.string.tip_hello_failed, Toast.LENGTH_SHORT).show();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    // 打招呼
    private void doSayHello(Friend friend, String text) {
        ChatMessage sayMessage = new ChatMessage();
        sayMessage.setFromUserId(coreManager.getSelf().getUserId());
        sayMessage.setFromUserName(coreManager.getSelf().getNickName());
        sayMessage.setToUserId(friend.getUserId());
        sayMessage.setContent(text);
        sayMessage.setType(XmppMessage.TYPE_TEXT); //文本类型
        sayMessage.setMsgType(ChatMessage.TYPE_HELLO);
        sayMessage.setMySend(true);
        sayMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_SUCCESS);
        sayMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
        sayMessage.setTimeSend(TimeUtils.sk_time_current_time());

        mAddhaoyouid = sayMessage.getPacketId();
        ChatMessageDao.getInstance().saveNewSingleChatMessage(friend.getOwnerId(), friend.getUserId(), sayMessage);
        // 这里最终调用smack的发送消息，
        coreManager.sendChatMessage(friend.getUserId(), sayMessage);
        EventBus.getDefault().post(sayMessage);// 通知群聊页添加当前消息
    }

    protected void onDestroy() {
        super.onDestroy();
        ListenerManager.getInstance().removeNewFriendListener(this);
    }
}